<template>
  <a-card :bordered="false">
    <a-row :gutter="8">
      <a-col :span="5">
        <a-menu style="width: 256px" mode="vertical" @select="handleSelect">
          <a-menu-item v-for="node in nodes" :key="node.nodeId" :title="node.name">
            <my-icon :type="node.icon" />
            {{ node.name }}
          </a-menu-item>
        </a-menu>
      </a-col>
      <a-col :span="19">
        <div class="table-page-search-wrapper">
          <a-form @submit="handleSubmit" :form="form">
            <a-form-item :wrapperCol="{ span: 22 }">
              <a-alert type="warning" showIcon >
                <span slot="message">温馨提示：若流程运行至未分配审批人员的审批节点时，流程将自动中断取消<br>
                  与集：此集合中设置的条件，将以与关系相连，查找满足所有条件的用户<br>
                  或集：此集合中设置的条件，都是相互独立的条件，根据每个条件查找到的用户将都放入审批列表中<br>
                  最终审批的用户为两个集合查找出的所有用户 </span>
              </a-alert></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['nodeId']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['andDeptHeader']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['orDeptHeader']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['andClassDirector']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['orClassDirector']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['andEqualDept']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['orEqualDept']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['secretary']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['office']" /></a-form-item>
            <a-form-item v-show="false"><a-input v-decorator="['applyer']" /></a-form-item>
            <!-- <a-form-item label="节点名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span>{{ mdl.name }}</span>
            </a-form-item> -->
            <a-row :gutter="20">
              <a-col :span="12">
                <a-card size="small" title="与集">
                  <a-checkbox @change="onChangeAndRole" :checked="andRoleChecked">角色</a-checkbox>
                  <a-checkbox @change="onChangeAndDept" :checked="andDeptChecked">部门</a-checkbox>
                  <a-checkbox @change="onChangeAndUser" :checked="andUserChecked">用户</a-checkbox>
                  <a-checkbox @change="onChangeAndDeptHeader" :checked="andDeptHeader">所属部门负责人</a-checkbox>
                  <a-checkbox @change="onChangeAndEqualDept" :checked="andEqualDept">与申请人相同部门</a-checkbox>
                  <a-checkbox @change="onChangeAndClassDirector" :checked="andClassDirector">所属班级班主任</a-checkbox>
                  <a-checkbox @change="onChangeSecretary" :checked="secretary">所属系书记</a-checkbox>
                  <a-checkbox @change="onChangeOffice" :checked="office">所属系学办主任</a-checkbox>
                  <a-checkbox @change="onChangeApplyer" :checked="applyer">申请人</a-checkbox>
                  <a-form-item label="选择角色" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="andRoleChecked">
                    <a-select v-decorator="['andRoleIds', { rules: [{ required: andRoleChecked, message: '至少选择一个角色' }] }]" mode="multiple" allowClear placeholder="角色">
                      <a-select-option v-for="(item, index) in roles" :key="index" :value="item.roleId">{{ item.roleName }}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="选择部门" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="andDeptChecked">
                    <a-tree-select
                      v-decorator="['andDeptIds', { rules: [{ required: andDeptChecked, message: '至少选择一个部门' }] }]"
                      :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                      :treeData="depts"
                      treeDefaultExpandAll
                      @change="handleChangeDept"
                      placeholder="部门"
                      multiple
                      allowClear
                    ></a-tree-select>
                  </a-form-item>
                  <a-form-item label="选择用户" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="andUserChecked">
                    <a-select v-decorator="['andUserIds', { rules: [{ required: andUserChecked, message: '至少选择一个用户' }] }]" mode="multiple" allowClear placeholder="用户">
                      <a-select-option v-for="(item, index) in users" :key="index" :value="item.userId">{{ item.userName + ' - ' + item.loginName }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card size="small" title="或集">
                  <a-checkbox @change="onChangeOrRole" :checked="orRoleChecked">角色</a-checkbox>
                  <a-checkbox @change="onChangeOrDept" :checked="orDeptChecked">部门</a-checkbox>
                  <a-checkbox @change="onChangeOrUser" :checked="orUserChecked">用户</a-checkbox>
                  <a-checkbox @change="onChangeOrDeptHeader" :checked="orDeptHeader">所属部门负责人</a-checkbox>
                  <a-checkbox @change="onChangeOrEqualDept" :checked="orEqualDept">与申请人相同部门</a-checkbox>
                  <a-checkbox @change="onChangeOrClassDirector" :checked="orClassDirector">所属班级班主任</a-checkbox>
                  <a-form-item label="选择角色" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="orRoleChecked">
                    <a-select v-decorator="['orRoleIds', { rules: [{ required: orRoleChecked, message: '至少选择一个角色' }] }]" mode="multiple" allowClear placeholder="角色">
                      <a-select-option v-for="(item, index) in roles" :key="index" :value="item.roleId">{{ item.roleName }}</a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="选择部门" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="orDeptChecked">
                    <a-tree-select
                      v-decorator="['orDeptIds', { rules: [{ required: orDeptChecked, message: '至少选择一个部门' }] }]"
                      :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                      :treeData="depts"
                      treeDefaultExpandAll
                      @change="handleChangeDept"
                      placeholder="部门"
                      multiple
                      allowClear
                    ></a-tree-select>
                  </a-form-item>
                  <a-form-item label="选择用户" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="orUserChecked">
                    <a-select v-decorator="['orUserIds', { rules: [{ required: orUserChecked, message: '至少选择一个用户' }] }]" mode="multiple" allowClear placeholder="用户">
                      <a-select-option v-for="(item, index) in users" :key="index" :value="item.userId">{{ item.userName + ' - ' + item.loginName }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-card>
              </a-col>
            </a-row>
            <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
              <a-button htmlType="submit" type="primary" :loading="confirmLoading" :disabled="mdl.type !== 1">提交</a-button>
              <a-button style="margin-left: 8px" @click="toList">返回</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import { Tree, Icon } from 'ant-design-vue'
import { STable } from '@/components'
import { getNodeList, getNodeInfo, updateNodeInfo } from '@/api/activiti'
import { getDeptList, getUserList, getRoleAll } from '@/api/system'
import pick from 'lodash.pick'
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1574906_mvhehmkaer.js' // 在 iconfont.cn 上生成
})
export default {
  name: 'TableList',
  components: {
    Tree,
    STable,
    MyIcon
  },
  data () {
    return {
      visible: false,
      labelCol: {
        lg: { span: 5 },
        sm: { span: 3 }
      },
      wrapperCol: {
        lg: { span: 18 },
        sm: { span: 12 }
      },
      mdl: {},
      confirmLoading: false,
      form: this.$form.createForm(this),
      depts: [],
      users: [],
      roles: [],
      nodes: [],

      andDeptChecked: false,
      andUserChecked: false,
      andRoleChecked: false,
      andDeptHeader: false,
      andClassDirector: false,
      andEqualDept: false,
      secretary: false,
      office: false,
      applyer: false,

      orDeptChecked: false,
      orUserChecked: false,
      orRoleChecked: false,
      orDeptHeader: false,
      orClassDirector: false,
      orEqualDept: false
    }
  },
  created () {
    const procDefId = this.$route.query.procDefId
    getNodeList(procDefId).then(res => {
      this.nodes = res.rows.map(n => {
        let icon = ''
        switch (n.type) {
          case 0:
            icon = 'icon-kaishi1'
            break
          case 2:
            icon = 'icon-jieshu'
            break
          default:
            icon = 'icon-shen'
        }
        return { name: n.name, nodeId: n.nodeId, icon: icon, type: n.type }
      })
    })
    getRoleAll().then(res => {
      this.roles = res.rows
    })
    getDeptList().then(res => {
      const data = res.rows
      this.buildtree(data, this.depts, 0)
    })
    getUserList({ userType: 2 }).then(res => {
      this.users = res.rows
    })
  },
  methods: {
    handleSelect (e) {
      const nodeId = e.key
      const node = this.nodes.filter(item => nodeId === item.nodeId)[0]
      if (node.type === 1) {
        getNodeInfo(nodeId).then(res => {
          const data = res.data
          this.mdl = Object.assign(data, node)
          this.orRoleChecked = data.orRoleIds.length > 0
          this.orDeptChecked = data.orDeptIds.length > 0
          this.orUserChecked = data.orUserIds.length > 0
          this.orDeptHeader = data.orDeptHeader
          this.orClassDirector = data.orClassDirector
          this.orEqualDept = data.orEqualDept

          this.andRoleChecked = data.andRoleIds.length > 0
          this.andDeptChecked = data.andDeptIds.length > 0
          this.andUserChecked = data.andUserIds.length > 0
          this.andDeptHeader = data.andDeptHeader
          this.andClassDirector = data.andClassDirector
          this.andEqualDept = data.andEqualDept

          this.secretary = data.secretary
          this.office = data.office
          this.applyer = data.applyer

          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.mdl, 'nodeId', 'orUserIds', 'orDeptIds', 'orRoleIds', 'orDeptHeader', 'orClassDirector', 'orEqualDept', 'andUserIds', 'andDeptIds', 'andRoleIds', 'andDeptHeader', 'andClassDirector', 'andEqualDept', 'secretary', 'office'))
          })
        })
      } else {
        this.$message.error('只能编辑任务节点')
        this.mdl = {}
        this.orRoleChecked = this.orDeptChecked = this.orUserChecked = this.orDeptHeader = this.orClassDirector = false
        this.andRoleChecked = this.andDeptChecked = this.andUserChecked = this.andDeptHeader = this.andClassDirector = false
      }
    },
    onChangeOrRole (e) {
      const value = e.target.checked
      this.orRoleChecked = value
      if (!value) {
        this.form.setFieldsValue({ orRoleIds: [] })
      }
    },
    onChangeAndRole (e) {
      const value = e.target.checked
      this.andRoleChecked = value
      if (!value) {
        this.form.setFieldsValue({ andRoleIds: [] })
      }
    },
    onChangeOrDept (e) {
      const value = e.target.checked
      this.orDeptChecked = value
      if (!value) {
        this.form.setFieldsValue({ orDeptIds: [] })
      }
    },
    onChangeAndDept (e) {
      const value = e.target.checked
      this.andDeptChecked = value
      if (!value) {
        this.form.setFieldsValue({ andDeptIds: [] })
      }
    },
    onChangeOrUser (e) {
      const value = e.target.checked
      this.orUserChecked = value
      if (!value) {
        this.form.setFieldsValue({ orUserIds: [] })
      }
    },
    onChangeAndUser (e) {
      const value = e.target.checked
      this.andUserChecked = value
      if (!value) {
        this.form.setFieldsValue({ andUserIds: [] })
      }
    },
    onChangeOrDeptHeader (e) {
      this.orDeptHeader = e.target.checked
      this.form.setFieldsValue({ orDeptHeader: this.orDeptHeader })
    },
    onChangeAndDeptHeader (e) {
      this.andDeptHeader = e.target.checked
      this.form.setFieldsValue({ andDeptHeader: this.andDeptHeader })
    },
    onChangeOrEqualDept (e) {
      this.orEqualDept = e.target.checked
      this.form.setFieldsValue({ orEqualDept: this.orEqualDept })
    },
    onChangeAndEqualDept (e) {
      this.andEqualDept = e.target.checked
      this.form.setFieldsValue({ andEqualDept: this.andEqualDept })
    },
    onChangeOrClassDirector (e) {
      this.orClassDirector = e.target.checked
      this.form.setFieldsValue({ orClassDirector: this.orClassDirector })
    },
    onChangeAndClassDirector (e) {
      this.andClassDirector = e.target.checked
      this.form.setFieldsValue({ andClassDirector: this.andClassDirector })
    },
    onChangeSecretary (e) {
      this.secretary = e.target.checked
      this.form.setFieldsValue({ secretary: this.secretary })
    },
    onChangeOffice (e) {
      this.office = e.target.checked
      this.form.setFieldsValue({ office: this.office })
    },
    onChangeApplyer (e) {
      this.applyer = e.target.checked
      this.form.setFieldsValue({ applyer: this.applyer })
    },
    buildtree (list, arr, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          var child = {
            key: item.deptId,
            value: item.deptId, // value是给modal的select用的，2者属性不一样
            title: item.deptName,
            scopedSlots: { title: 'title' },
            children: []
          }
          this.buildtree(list, child.children, item.deptId)
          if (child.children.length === 0) {
            delete child.children
          }
          arr.push(child)
        }
      })
    },
    handleChangeDept (value, label, extra) {
      console.log(extra)
      if (extra.selected && extra.triggerNode.$children.length > 0) {
        this.$message.error('不能选择父节点 ' + extra.triggerNode.title)
        value.splice(value.findIndex(item => item === extra.triggerValue), 1)
      }
    },
    toList () {
      this.$router.push({ name: 'procDefList' })
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          updateNodeInfo(values)
            .then(res => {
              if (res.code === 0) {
                this.$message.success('保存成功')
                // this.toList()
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(() => {
              this.$message.error('系统错误，请稍后再试')
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-menu-vertical {
  .ant-menu-item {
    display: flex;
    .anticon {
      font-size: 24px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
